package com.hjq.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hjq.exception.ForeignKeyException;
import com.hjq.mapper.ClazzMapper;
import com.hjq.pojo.Clazz;
import com.hjq.pojo.queryparam.ClazzQueryParam;
import com.hjq.pojo.PageResult;
import com.hjq.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    ClazzMapper clazzMapper;
    @Override
    public PageResult<Clazz> findByPage(ClazzQueryParam clazzQueryParam) {
        PageResult<Clazz> pageResult = new PageResult<>();
        // 使用PageHelper来自动分页以及计算总页数，total，row，需要在查询操作之后在set
        Page<Object> page = PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        List<Clazz> list = clazzMapper.findByPage(clazzQueryParam);
        // 对班级添加 开课状态
        // 当前时间早于开始时间，未开课；当前时间，在开始时间之后，同时结束时间之前，在读，否则为已结课
        list.forEach( clazz -> clazz.setStatus( clazz.getBeginDate().isAfter(LocalDate.now()) ? "未开课" : clazz.getEndDate().isAfter(LocalDate.now()) ? "在读" : "已结课"));
        pageResult.setTotal(page.getTotal());
        pageResult.setRows(list);
        return  pageResult;
    }

    @Override
    public void deleteById(Integer id) {
        Integer countOfClazz = clazzMapper.getCountOfClazz(id);
        if (countOfClazz > 0) {
            throw new ForeignKeyException("该班级下有学生，请先删除该班级下的学生");
        }
        clazzMapper.deleteById(id);
    }

    @Override
    public Clazz findById(Integer id) {
        return clazzMapper.findById(id);
    }

    @Override
    public void insert(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazz.setCreateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public List<Clazz> findAll() {
        return clazzMapper.findAll();
    }
}
